<template>
    <a-modal :keyboard="false" :maskClosable="false" title="工单移交" :open="visible" :width="800" :confirmLoading="loading" centered @ok="handleSubmit" @cancel="handleCancel">
        <a-table :size="10" :columns="dynamicColumns" :data-source="modelRef.orderList" row-key="id" :scroll="{ y: 300 }">
            <template #bodyCell="{ record, column }">
                <template v-if="column.dataIndex === 'org'">
                    <a-tooltip :content="[record.corpName, record.deptName, record.jobName].filter(Boolean).join('/')">
                        {{ [record.corpName, record.deptName, record.jobName].filter(Boolean).join('/') }}
                    </a-tooltip>
                </template>
            </template>
        </a-table>

        <a-row :gutter="16" type="flex" justify="start">
            <a-col :xs="12" :sm="12" :md="12">
                <a-form layout="horizontal">
                    <a-form-item label="接收人">
                        <a-select
                            v-model:value="modelRef.userId"
                            allowClear
                            placeholder="选择接收人"
                            :options="modelRef.userList"
                            style="width: 100%"
                            :field-names="{ label: 'name', value: 'id' }"
                        />
                    </a-form-item>
                </a-form>
            </a-col>
        </a-row>
    </a-modal>
</template>

<script lang="ts">
    import type { PropType } from 'vue';
    import { defineComponent, reactive, ref, watchEffect, watch, Ref } from 'vue';
    import { Form } from 'ant-design-vue';
    import { cloneDeep, isEmpty } from 'lodash-es';
    import { useTableDynamicColumns } from '@/utils/hooks/useTableColumn';
    import { orderHandOn, getUserListByHandOn } from '@/api/order/mine-list';
    import type { Pagination, TableColumn } from '@/typing';
    import { statusMap as stateMap } from './common';
    import { message } from 'ant-design-vue';

    const baseColumns: TableColumn[] = [
        {
            title: '工单编号',
            dataIndex: 'orderNum',
        },
        {
            title: '工单状态',
            dataIndex: 'orderState',
            customRender: ({ text }) => stateMap[text],
        },
        {
            title: '项目名称',
            dataIndex: 'projectName',
            ellipsis: true,
        },
        {
            title: '当前负责人',
            dataIndex: 'orderChargePerson',
            ellipsis: true,
        },
    ];

    export default defineComponent({
        props: {
            visible: {
                type: Boolean,
                required: true,
            },
            model: {
                type: Object as PropType<any>,
                default: () => [],
            },
        },
        emits: ['cancel', 'confirm', 'success'],
        setup(props, { emit }) {
            const loading = ref(false);

            const { state: columnState, dynamicColumns, dynamicColumnItems } = useTableDynamicColumns(baseColumns, { needRowIndex: false });
            const modelRef = reactive<any>({
                userId: '',
                orderList: [],
            });
            const rulesRef = reactive({
                userId: [{ required: true, message: '请选择' }],
            });
            const { validateInfos, resetFields } = Form.useForm(modelRef, rulesRef);

            // 记录初始值
            const initValues = reactive({});
            watch(
                () => props.visible,
                () => {
                    Object.assign(initValues, cloneDeep(props.model));
                },
            );
            watchEffect(() => {
                if (props.visible) {
                    if (props.model) {
                        modelRef.orderList = props.model;
                        getUserListByHandOn(
                            modelRef.orderList.map(item => ({
                                id: item.id,
                                projectCode: item.projectCode,
                            })),
                        ).then(res => {
                            modelRef.userList = res.data || [];
                        });
                    }
                }
            });

            const handleCancel = () => {
                // resetFields();
                Object.keys(modelRef).forEach(key => {
                    delete modelRef[key];
                });
                emit('cancel');
            };

            const handleSubmit = async () => {
                if (modelRef.userId) {
                    orderHandOn({
                        userId: modelRef.userId,
                        orderList: modelRef.orderList.map(item => ({
                            id: item.id,
                            projectCode: item.projectCode,
                            orderChargePerson: item.orderChargePerson,
                        })),
                    })
                        .then(res => {
                            if (res.data) {
                                message.success('操作成功');
                                emit('success');
                                handleCancel();
                            }
                        })
                        .finally(() => {
                            loading.value = false;
                        });
                } else {
                    message.warning('请选择接收人');
                }
            };

            return {
                loading,

                columnState,
                dynamicColumns,
                dynamicColumnItems,

                modelRef,
                validateInfos,
                resetFields,

                handleSubmit,
                handleCancel,

                initValues,
            };
        },
    });
</script>

<style lang="less" scoped></style>
